﻿using System.Drawing;
using System.Windows.Forms;

namespace dgmobile
{
  public partial class Form1 : Form
  {
    /// <summary>
    /// Fills dataGridView with data from DB.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void FillGrid(object sender, FormClosedEventArgs e)
    {
      //Fetching data.
      dataGridView.DataSource = DB.ListData();

      if(dataGridView.DataSource == null)
      {
        return;
      }

      //Formatting column headers.
      dataGridView.ColumnHeadersDefaultCellStyle.Font = new Font("Microsoft Sans Serif", 14F, GraphicsUnit.Pixel);
      //Making columns unsortable and removing context menu from headers.
      foreach(DataGridViewColumn col in dataGridView.Columns)
      {
        col.SortMode = DataGridViewColumnSortMode.NotSortable;
        col.HeaderCell.ContextMenuStrip = null;
      }
      //Auto size it. Bitches looooove auto size.
      dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
      //No ID row visible because that's super secret info. For realz.
      dataGridView.Columns[0].Visible = false;
    }

    /// <summary>
    /// Executes the "login" and hides data entering if invalid user.
    /// </summary>
    /// <param name="chapa">Valid id for DB lookup.</param>
    private void ChangeUser(string chapa)
    {
      User user = DB.GetUser(textBoxChapa.Text);
      if(user != null)
      {
        Config.Operator = user;
        labelOperatorName.Text = user.Nome; ;
        labelOperatorDG.Text = "DG " + user.DG;
        groupBox2.Enabled = true;
        contextMenuStrip1.Enabled = true;
      }
      else
      {
        Config.Operator = null;
        textBoxChapa.Focus();
        textBoxChapa.SelectionStart = 0;
        textBoxChapa.SelectionLength = 6;
        labelOperatorName.Text = "Informe uma chapa válida.";
        labelOperatorDG.Text = "-";
        groupBox2.Enabled = false;
        contextMenuStrip1.Enabled = false;
      }
    }

    /// <summary>
    /// Brings up the chosen form for data entry.
    /// </summary>
    /// <param name="type"></param>
    private void Popup(int type)
    {
      Config.Popup = new Form2(type);
      //Refreshes grid upon popup closing.
      Config.Popup.FormClosed += new FormClosedEventHandler(FillGrid);
      Config.Popup.ShowDialog(this);
    }

    private void UpdateCheck(object sender, System.EventArgs e)
    {
      if(Config.UpdateAvailable())
      {
        UpdateClock.Stop();
        MessageBox.Show(this, "Nova atualização disponível.\n\nO aplicativo será encerrado agora e atualizado na próxima vez que for iniciado.", "Atualização de aplicativo");
        System.Diagnostics.Process.GetCurrentProcess().Kill();
      }
    }
  }
}